import json
import time
from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_page
from decimal import Decimal
from SpiderFile.DaiLianTong.index import DaiLianTongSpider
from SpiderFile.DaiLianWanZi.index import DaiLianWanZi
from BloodSpiderModel.spider_tools.common_utils import GeneralToolkit
from PublicFunction.MoneyUtils import safe_to_number, calculate_security_deposit
from BloodSpiderAPI import models
from django.db.models import Q, Sum
from BloodSpiderAPI.apis.game.wzry import utils as wzry_utils
from datetime import datetime, timedelta

gen_toolkit = GeneralToolkit()

# 代理通
dlt = DaiLianTongSpider()
dlt_user_id = str(dlt.auth_config["UserID"])
dlt_token = dlt.auth_config["Token"]
dlt_uid = dlt.auth_config["UID"]

# 代练丸子, 不需要用户认证,脚本已内置
dlwz = DaiLianWanZi()

with open("db_small_json/dailianwanzi/English_Sensitive_Words_for_Order_Post_Titles_on_Dai_lian_Wanzi.json", "r",
          encoding="utf-8") as f:
    # 敏感词列表
    sensitive_words = json.load(f)


# ========== 代练通 接口 ==========
def dlt_UserInfoList(request):
    """
    获取用户信息列表
    """
    try:
        dlt_user_info = dlt.UserInfoList(UserID=dlt_user_id, Token=dlt_token)
        return response_dict(data=dlt_user_info)
    except Exception as e:
        return response_dict(code=1, message=f"获取用户信息列表失败: {str(e)}")


# 获取游戏单子 LevelOrderList
def dlt_LevelOrderList(request):
    """
    获取游戏单子 LevelOrderList
    """
    try:
        Price_Str = request.GET.get("Price_Str", "10_20")
        SearchStr = request.GET.get("SearchStr", "")
        dlt_level_order_list = dlt.LevelOrderList(Price_Str=Price_Str, UserID=dlt_user_id, Token=dlt_token, SearchStr=SearchStr)
        for order_item in dlt_level_order_list["LevelOrderList"]:
            order_item["Amount"] = order_item["Price"]
            Zone = order_item["Zone"]
            if Zone == "安卓WX":
                Zone = "安卓微信"
            elif Zone == "苹果WX":
                Zone = "苹果微信"
            order_item["GameRegionName"] = Zone
            order_item["Hour"] = order_item["TimeLimit"]
            order_item["OrderSourceID"] = order_item["SerialNo"]
            order_item["ReceivingMargin"] = order_item["Ensure1"]
            order_item["ReceivingEfficiencyFee"] = order_item["Ensure2"]
            order_item["OrderSourceName"] = "代练通"
        return response_dict(data=dlt_level_order_list)
    except Exception as e:
        return response_dict(code=1, message=str(e))


# 获取游戏单子详情 LevelOrderDetail
def dlt_LevelOrderDetail(request):
    """
    获取游戏单子详情 LevelOrderDetail
    """
    try:
        OrderID = request.GET.get("OrderID", "")
        if not OrderID or OrderID == "":
            return response_dict(code=400, msg="OrderID 必须提供")
        dlt_level_order_detail = dlt.LevelOrderDetail(OrderID=OrderID, UserID=dlt_user_id, Token=dlt_token)
        if dlt_level_order_detail["code"] != 0:
            return response_dict(code=dlt_level_order_detail["code"], message=dlt_level_order_detail["message"])
        return response_dict(data=dlt_level_order_detail)
    except Exception as e:
        return response_dict(code=1, message=f"获取游戏单子详情失败: {str(e)}")


# 接收订单 LevelOrderReceive
def dlt_LevelOrderReceive(request):
    """
    接收订单 LevelOrderReceive
    """
    try:
        OrderID = request.GET.get("OrderID", "")
        PayPassword = request.GET.get("PayPassword", "")
        if not OrderID or OrderID == "":
            return response_dict(code=1, message="OrderID 必须提供")
        if not PayPassword or PayPassword == "":
            return response_dict(code=1, message="PayPassword 必须提供")
        dlt_level_order_receive = dlt.receive_order(order_id=OrderID, PayPass=PayPassword, UserID=dlt_user_id,
                                                    Token=dlt_token, UID=dlt_uid)

    #     dlt_level_order_receive = {
    #     "Result": 1,
    #     "Err": "接手成功.",
    #     "FirstAccept": 0,
    #     "WXCustomer": "扫码添加21",
    #     "Mobile": "19295757544",
    #     "GameID": 107,
    #     "PublishUserID": 24127744,
    #     "Popup": 0,
    #     "Msg": ""
    # } 
        if dlt_level_order_receive["Result"] == 1:
            # 接单成功, 更新订单状态
            models.OrderList.objects.filter(order_source_id=OrderID).update(status=2)
        else:
            return response_dict(code=1, message=dlt_level_order_receive["Err"])

        return response_dict(data=dlt_level_order_receive)
    except Exception as e:
        return response_dict(code=1, message=f"接收订单失败: {str(e)}")


# 获取游戏单子号主信息 LevelOrderOwnerInfo
def dlt_LevelOrderOwnerInfo(request):
    """
    获取游戏单子号主信息 LevelOrderOwnerInfo
    """
    try:
        OrderID = request.GET.get("OrderID", "")
        if not OrderID or OrderID == "":
            return response_dict(code=400, msg="OrderID 必须提供")
        dlt_level_order_info = dlt.LevelOrderDetail(OrderID=OrderID, UserID=dlt_user_id, Token=dlt_token)
        if dlt_level_order_info["code"] != 0:
            return response_dict(code=1, message=dlt_level_order_info["message"])
   
        result = {
            "GameAcc": dlt_level_order_info["GameAcc"],
            "GamePass": dlt_level_order_info["GamePass"],
            "GameMobile": dlt_level_order_info["GameMobile"],
            "Actor": dlt_level_order_info["Actor"],
            "Game": dlt_level_order_info["Game"],
            "Zone": dlt_level_order_info["Zone"],
            "Title": dlt_level_order_info["Title"],
        }
        return response_dict(data=result)
    except Exception as e:
        return response_dict(code=1, message=f"获取游戏单子号主信息失败: {str(e)}")

# 搜索订单是否存在
def dlt_SearchOrderExist(request):
    """
    搜索订单是否存在
    """
    try:
        OrderID = request.GET.get("OrderID", "")
        if not OrderID or OrderID == "":
            return response_dict(code=1, message="OrderID 必须提供")
        dlt_search_order_exist = dlt.search_order(order_id=OrderID, UserID=dlt_user_id, Token=dlt_token)
        if dlt_search_order_exist["RecordCount"] == 0:
            return response_dict(code=1, message="订单不存在")
        return response_dict(data=dlt_search_order_exist['LevelOrderList'][0], message="订单存在")
    except Exception as e:
        return response_dict(code=1, message=f"搜索订单是否存在失败: {str(e)}")



# ========== 代练丸子 接口 ==========

#  获取订单列表-v2版本：支持按照状态获取
def dlwz_GetOrderList(request):
    """
    获取订单列表-v2版本：支持按照状态获取
    """
    tableType = request.GET.get("TableType", 0)  # 订单状态, 可选值是: 0-全部, 1-待接单, 2-已接单, 3-已完成, 4-已取消
    dlwz_order_list = dlwz.get_order_list_v2(tableType=tableType)
    return response_dict(data=dlwz_order_list)



# 获取我的余额
def dlwz_GetMyBalance(request):
    """
    获取我的余额
    """
    try:
        dlwz_my_balance = dlwz.get_my_balance()
        return response_dict(data=dlwz_my_balance)
    except Exception as e:
        print("获取我的余额失败:", e)
        return response_dict(code=1, message=f"获取我的余额失败: {str(e)}")


# 发布订单
def dlwz_PublishOrder(request):
    """
    发布订单
    """
    try:
        title = request.GET.get("Title")
        if not title or title == "":
            return response_dict(code=1, message="Title 必须提供")
        amount = safe_to_number(request.GET.get("Amount"))
        account_id = request.GET.get("account_id")
        playerPhone = request.GET.get("PlayerPhone", "3837190115")  # 玩家手机号
        hour = request.GET.get("Hour")  # 游戏时长, 单位是小时
        gameRegionName = request.GET.get("GameRegionName")  # 游戏区域, 只能是'安卓QQ', 可选值是: 安卓微信、苹果QQ、苹果微信
        # 抽成
        commissionRate = amount * 0.2  # 抽成比例, 可选值是: 0.1-0.9

        posting = amount - commissionRate  # 订单金额 = 玩家金额 * 抽成比例

        # 来源平台参数
        order_source_name = request.GET.get("OrderSourceName", "代练通")
        order_source_id = request.GET.get("OrderSourceID")
        receiving_margin = safe_to_number(request.GET.get("ReceivingMargin", 0))  # 接单保证金
        receiving_efficiency_fee = safe_to_number(request.GET.get("ReceivingEfficiencyFee", 0))  # 接单效率保证金
        security_deposit = calculate_security_deposit(posting, receiving_margin + receiving_efficiency_fee)
        if security_deposit is None or security_deposit <= 0 or security_deposit < 20:
            print(f"security_deposit: {security_deposit}")
            return response_dict(code=1, message="安全保证金参数错误")

        if not account_id or account_id == "" or account_id == "null":
            return response_dict(code=1, message="account_id 必须提供")

        # 安全性校验
        if not order_source_id or order_source_id == "":
            return response_dict(code=1, message="OrderSourceID 必须提供")
        # 检测订单标题是否包含敏感词
        if gen_toolkit.check_common_substrings(title, sensitive_words):
            return response_dict(
                code=1,
                message="订单标题包含敏感词",
            )

        # gameRegionName 校验
        if gameRegionName not in ["安卓QQ", "安卓微信", "苹果QQ", "苹果微信"]:
            return response_dict(
                code=1,
                message="游戏区域参数错误",
            )
        # amount 校验
        if posting is None:
            print(f"posting: {posting}")
            return response_dict(
                code=1,
                message="金额参数错误",
            )

        # commissionRate 如果少于4元也算失败
        if commissionRate < 3:
            return response_dict(
                code=1,
                message="抽成比例不能少于4元",
            )
        # hour 校验
        if hour is None:
            return response_dict(
                code=1,
                message="游戏时长参数错误",
            )
        # 判断数据库是否有来源平台ID的记录
        if models.OrderList.objects.filter(order_source_id=order_source_id).exists():
            return response_dict(
                code=1,
                message="该来源平台ID已存在订单",
            )

        dlwz_publish_order = dlwz.publish_order(
            title=title,
            amount=posting,
            securityDeposit=security_deposit / 2,
            efficiencyDeposit=security_deposit / 2,
            playerPhone=playerPhone,
            gameRegionName=gameRegionName,
            hour=hour,
        )


        # dlwz_publish_order = {
        #     "data": {
        #         "tradeNo": wzry_utils.generate_random_str(),
        #         "status": 2,
        #         "gameRegionName": "安卓QQ",
        #     },
        #     "message": "您的订单已",
        # }
        if "您的订单已" not in dlwz_publish_order["message"]:
            print(f"dlwz_publish_order您的订单已: {dlwz_publish_order}, 发布的价格: {posting}")
            return response_dict(
                code=1,
                message=dlwz_publish_order["message"],
                data=dlwz_publish_order["data"],
            )
     
        # 订单发布成功
        order_info = models.OrderList.objects.create(
            account_id=account_id,
            order_name=title,  # 订单名称
            order_source_name=order_source_name,  # 来源平台名称
            posting_platform_name="代练丸子",  # 发布平台名称
            order_source_id=order_source_id,  # 来源平台订单ID
            posting_platform_id=dlwz_publish_order["data"]["tradeNo"],  # 发布平台订单ID
            receiving_price=amount,  # 接单价格
            receiving_margin=receiving_margin,  # 接单保证金
            receiving_efficiency_fee=receiving_efficiency_fee,  # 接单效率保证金
            receiving_delivery_time=hour,  # 接单交付时间
            receiving_server=gameRegionName,  # 接单服务器
            posting_price=posting,  # 发布价格
            posting_security_fee=security_deposit / 2,  # 发布安全保证金
            posting_efficiency_fee=security_deposit / 2,  # 发布效率保证金

        )

        return response_dict(data={
            "dlwz_publish_order": dlwz_publish_order["data"],
            "order_info": wzry_utils.order_info_to_dict(order_info),
        }, message=dlwz_publish_order["message"])
    except Exception as e:
        print("发布订单异常", e)
        return response_dict(code=1, message=str(e))


# 取消订单
def dlwz_CancelOrder(request):
    """
    取消订单
    """
    try:
        order_id = request.GET.get("OrderID", "")
        if not order_id or order_id == "":
            return response_dict(code=1, message="OrderID 必须提供")
        dlwz_cancel_order = dlwz.cancel_order(orderId=order_id)
        order_model =  models.OrderList.objects.filter(posting_platform_id=order_id)
        # print("取消订单返回结果: ", dlwz_cancel_order)
        if dlwz_cancel_order["code"] != 10000:
            # 在代练丸子中查询当期的状态
            order = dlwz.query_order(orderId=order_id)
            # print("客户端发送取消订单请求, 当前在代练丸子的状态是: ", order)
            if order["code"] == 10000 and order["data"]["ordersList"][0]["status"] in [14, 10, 12, 11]:
                # 在数据库中标记取消
                order_model.update(status=4)
                return response_dict(data=dlwz_cancel_order, message="取消订单成功")
            elif order["data"]["ordersList"][0]["status"] in [3]:
                order_model.update(status=2)
                return response_dict(data=dlwz_cancel_order, message="该订单已被接手")
            elif order["data"]["ordersList"][0]["status"] in [9]:
                return response_dict(code=1, message="该订单正在仲裁中")
            return response_dict(code=1, message=dlwz_cancel_order["message"])
        # 在数据库中标记取消
        order_model.update(status=4)
        return response_dict(data=dlwz_cancel_order, message="取消订单成功")
    except Exception as e:
        return response_dict(code=1, message=f"取消订单失败: {str(e)}")


# ========== 订单管理接口 ==========

# 获取订单列表（支持模糊查询）
def get_order_list(request):
    """
    获取订单列表，支持基于订单来源ID、订单发布平台ID的模糊查询和状态筛选
    """
    try:
        # 获取查询参数
        order_source_id = request.GET.get("order_source_id", "")
        status = request.GET.get("status")
        
        # 构建查询条件
        accounts = models.Account.objects.filter(Q(create_by=request.user) | Q(current_owner=request.user))
        query = Q() # 初始化查询条件，用于组合多个筛选条件
        search_fields = Q() # 初始化搜索字段，用于组合多个模糊查询条件
        
        # 订单来源ID或发布平台ID的模糊查询
        if order_source_id:
            search_fields |= Q(order_source_id__icontains=order_source_id)
            search_fields |= Q( posting_platform_id__icontains=order_source_id)
            search_fields |= Q(order_id__icontains=order_source_id)
            query &= search_fields
        
        # 状态筛选
        if status is not None and status != "":
            try:
                status_value = int(status)
                # 验证状态值是否在允许的范围内
                valid_status = [choice[0] for choice in models.OrderList.STATUS_CHOICES]
                if status_value not in valid_status:
                    return response_dict(code=400, message=f"无效的订单状态值: {status}, 允许的状态值为: {', '.join(map(str, valid_status))}")
                # 添加状态条件
                query &= Q(status=status_value)
            except ValueError:
                return response_dict(code=400, message=f"无效的订单状态值: {status}, 状态值必须为整数")
        
        # 执行查询
        orders = models.OrderList.objects.filter(account__in=accounts).filter(query)
        # 分页处理
        page_size = int(request.GET.get('page_size', 10))
        page = int(request.GET.get('page', 1))
        paginated_data = get_page(orders, page_size=page_size, page_num=page)
        if not paginated_data:
            return response_dict(code=1, message="没有更多数据", data=[])
        # 转换为字典列表
        order_list = [wzry_utils.order_info_to_dict(order) for order in paginated_data["page"]["object_list"]]
        del paginated_data["page"]["object_list"]
        
        return response_dict(data=order_list, message="获取订单列表成功")
    except Exception as e:
        return response_dict(code=1, message=f"获取订单列表失败: {str(e)}")


# 获取单个订单详情
def get_order_detail(request):
    """
    获取单个订单详情
    """
    try:
        order_id = request.GET.get("order_id", "")
        if not order_id:
            return response_dict(code=400, message="order_id 必须提供")
        
        order = models.OrderList.objects.get(order_id=order_id)
        return response_dict(data=wzry_utils.order_info_to_dict(order), message="获取订单详情成功")
    except models.OrderList.DoesNotExist:
        return response_dict(code=404, message="订单不存在")
    except Exception as e:
        return response_dict(code=1, message=f"获取订单详情失败: {str(e)}")


# 更新订单信息（仅更新传入的字段）
def update_order(request):
    """
    更新订单信息，仅更新传入的字段
    """
    # 获取订单ID
    order_id = request.POST.get("order_id", "")
    if not order_id:
        return response_dict(code=400, message="order_id 必须提供")
    
    try:
        order = models.OrderList.objects.get(order_id=order_id)
        if order.status == 3:
            if int(request.POST.get("status")) != 3:
                # 减去余额
                wzry_utils.update_account_balance(order.account, order.completed_profit, is_add=False)
        # 获取所有可能的字段
        fields_to_update = {
            "order_source_name": request.POST.get("order_source_name"),
            "posting_platform_name": request.POST.get("posting_platform_name"),
            "order_source_id": request.POST.get("order_source_id"),
            "posting_platform_id": request.POST.get("posting_platform_id"),
            "order_name": request.POST.get("order_name"),
            "receiving_price": request.POST.get("receiving_price"),
            "receiving_margin": request.POST.get("receiving_margin"),
            "receiving_efficiency_fee": request.POST.get("receiving_efficiency_fee"),
            "receiving_delivery_time": request.POST.get("receiving_delivery_time"),
            "receiving_server": request.POST.get("receiving_server"),
            "posting_price": request.POST.get("posting_price"),
            "posting_security_fee": request.POST.get("posting_security_fee"),
            "posting_efficiency_fee": request.POST.get("posting_efficiency_fee"),
            "status": request.POST.get("status"),
            "owner_contact": request.POST.get("owner_contact"),
            "dailian_contact": request.POST.get("dailian_contact"),
            "remark": request.POST.get("remark"),
            "completed_profit": request.POST.get("completed_profit"),
        }
        
        # 仅更新有值的字段
        updated_count = 0
        # 作用: 遍历所有可能的字段，仅更新有值的字段
        for field, value in fields_to_update.items():
            if value is not None and value != "" and value != "null":
                # 处理特定字段类型转换
                if field in ["receiving_price", "receiving_margin", "receiving_efficiency_fee", 
                            "posting_price", "posting_security_fee", "posting_efficiency_fee"]:
                    setattr(order, field, safe_to_number(value))
                elif field == "status":
                    setattr(order, field, int(value))
                elif field == "remark":
                    # 为remark字段添加特殊处理：将新内容追加到原有内容之后
                    existing_remark = getattr(order, field, "")
                    if existing_remark:
                        # 如果原有内容不为空，添加分隔符后追加新内容
                        new_remark = f"{existing_remark}\n{value}"
                    else:
                        # 如果原有内容为空，直接使用新内容
                        new_remark = value
                    setattr(order, field, new_remark)
                else:
                    setattr(order, field, value)
                updated_count += 1
        
        if updated_count > 0:
            order.save()
            if order.status == 3:
                # 更新账号的余额
                wzry_utils.update_account_balance(order.account, order.completed_profit)
            elif order.status == 6 and Decimal(order.completed_profit) > 0:
                # 减去余额
                wzry_utils.update_account_balance(order.account, order.completed_profit, is_add=False)
                
                
            return response_dict(data=wzry_utils.order_info_to_dict(order), 
                                message=f"成功更新 {updated_count} 个字段")
        else:
            return response_dict(code=400, message="没有提供需要更新的字段")
            
    except models.OrderList.DoesNotExist:
        return response_dict(code=404, message="订单不存在")
    except Exception as e:
        return response_dict(code=1, message=f"更新失败: {str(e)}")


# 删除订单
def delete_order(request):
    """
    删除订单
    """
    order_id = request.POST.get("order_id", "")
    if not order_id:
        return response_dict(code=400, message="order_id 必须提供")
    
    try:
        order = models.OrderList.objects.get(order_id=order_id)
        order.delete()
        return response_dict(message="删除订单成功")
    except models.OrderList.DoesNotExist:
        return response_dict(code=404, message="订单不存在")
    except Exception as e:
        return response_dict(code=1, message=f"删除失败: {str(e)}")


# 获取全部订单
def get_all_orders(request):
    """
    获取所有订单
    """
    try:
        orders = models.OrderList.objects.all()
        
        # 转换为字典列表
        order_list = []
        for order in orders:
            order_list.append(wzry_utils.order_info_to_dict(order))
        
        return response_dict(data={
            "orders": order_list,
            "total": len(order_list)
        }, message="获取全部订单成功")
    except Exception as e:
        return response_dict(code=1, message=f"获取全部订单失败: {str(e)}")

# 获取订单统计数据
def get_order_statistics(request):
    """
    获取订单统计数据
    返回：总订单数量、成功订单数、已取消订单数、总收入（按时间维度：今日、本周、本月）
    """
    try:
        # 获取当前时间
        now = datetime.now()
        
        # 计算时间范围
        today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
        week_start = now - timedelta(days=now.weekday())
        week_start = week_start.replace(hour=0, minute=0, second=0, microsecond=0)
        month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        
        # 统计总订单数量
        total_orders = models.OrderList.objects.count()
        
        # 统计成功订单数量（状态为3）
        completed_orders = models.OrderList.objects.filter(status=3).count()
        
        # 统计已取消订单数量（状态为4）
        cancelled_orders = models.OrderList.objects.filter(status=4).count()
        
        # 统计已失败订单数量（状态为6）
        failed_orders = models.OrderList.objects.filter(status=6).count()
        
        # 统计处理中订单数量（状态为5）
        pending_orders = models.OrderList.objects.filter(status=5).count()
        
        # 计算总收入（所有订单的completed_profit之和）
        total_profit = models.OrderList.objects.filter(completed_profit__isnull=False).aggregate(
            total=Sum('completed_profit')
        )['total'] or 0
        
        # 计算今日总收入
        today_profit = models.OrderList.objects.filter(
            completed_profit__isnull=False,
            create_time__gte=today_start
        ).aggregate(
            total=Sum('completed_profit')
        )['total'] or 0
        
        # 计算本周总收入
        week_profit = models.OrderList.objects.filter(
            completed_profit__isnull=False,
            create_time__gte=week_start
        ).aggregate(
            total=Sum('completed_profit')
        )['total'] or 0
        
        # 计算本月总收入
        month_profit = models.OrderList.objects.filter(
            completed_profit__isnull=False,
            create_time__gte=month_start
        ).aggregate(
            total=Sum('completed_profit')
        )['total'] or 0
        
        # 统计本周内每一天的收入金额和订单发布数量
        week_daily_trend = []
        
        # 计算本周一的日期
        monday = now - timedelta(days=now.weekday())
        monday = monday.replace(hour=0, minute=0, second=0, microsecond=0)
        
        # 遍历本周的每一天（周一到周日）
        for i in range(7):
            current_date = monday + timedelta(days=i)
            next_date = current_date + timedelta(days=1)
            
            # 统计当天的订单总数
            daily_orders = models.OrderList.objects.filter(
                create_time__gte=current_date,
                create_time__lt=next_date
            ).count()
            
            # 统计当天的收入总和
            daily_profit = models.OrderList.objects.filter(
                completed_profit__isnull=False,
                create_time__gte=current_date,
                create_time__lt=next_date
            ).aggregate(
                total=Sum('completed_profit')
            )['total'] or 0
            
            # 格式化日期显示（周一至周日）
            weekday_names = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
            date_display = weekday_names[i]
            
            week_daily_trend.append({
                "date": date_display,
                "date_value": current_date.strftime("%Y-%m-%d"),
                "orders_count": daily_orders,
                "profit": float(daily_profit)
            })
        
        # 构建响应数据
        statistics_data = {
            "total_orders": total_orders, # 总订单数量
            "completed_orders": completed_orders, # 成功订单数
            "cancelled_orders": cancelled_orders, # 已取消订单数
            "failed_orders": failed_orders, # 已失败订单数
            "pending_orders": pending_orders, # 处理中订单数
            "total_profit": float(total_profit), # 总收入
            "today_profit": float(today_profit), # 今日总收入
            "week_profit": float(week_profit), # 本周总收入
            "month_profit": float(month_profit), # 本月总收入
            "week_daily_trend": week_daily_trend, # 本周每日趋势数据
            "update_time": now.strftime("%Y-%m-%d %H:%M:%S") # 更新时间
        }
        
        return response_dict(data=statistics_data, message="获取订单统计数据成功")
    except Exception as e:
        return response_dict(code=1, message=f"获取订单统计数据失败: {str(e)}")


# 返回status的全部状态
def get_order_status_list(request):
    status_list = [{'value': value, 'name': text, "disabled": False} for value, text in models.OrderList.STATUS_CHOICES]
    return response_dict(message="获取订单状态列表成功", data=status_list)